<template>
  <el-dialog :title="title" :visible.sync="visiable" width="85%" :before-close="handleClose">
    <el-form ref="formData" :model="formData" label-width="100px"  >
      <el-form-item label="标题:">
        <el-input v-model="formData.title" v-if="isEdit"></el-input>
        <el-input v-model="formData.title" v-if="!isEdit" readonly></el-input>
      </el-form-item>
      <el-form-item label="描述:">
        <el-input v-model="formData.des" v-if="isEdit"></el-input>
        <el-input v-model="formData.des" v-if="!isEdit" readonly></el-input>
      </el-form-item>
      <el-form-item label="分类:">
        <el-select v-model="checkedCategoryId" clearable filterable style="width:120px;" disabled v-if="!isEdit">
          <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.name" :value="item.categoryId"></el-option>
        </el-select>
        <el-select v-model="checkedCategoryId" clearable filterable style="width:120px;" v-if="isEdit">
          <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.name" :value="item.categoryId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签：" prop="labelIds">
        <el-select v-model="checkedLabelIds" multiple placeholder="请选择" v-if="isEdit">
          <el-option
            v-for="item in labelList"
            :key="item.labelId"
            :label="item.name"
            :value="item.labelId">
          </el-option>
        </el-select>
        <el-select v-model="checkedLabelIds" multiple placeholder="请选择" v-if="!isEdit" disabled>
          <el-option
            v-for="item in labelList"
            :key="item.labelId"
            :label="item.name"
            :value="item.labelId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主图">
        <img :src="formData.img" style="width:178px; height:178px; display: block" v-if="!isEdit"/>
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadMainImg" v-if="isEdit">
          <img style="width:178px; height:178px; display: block" v-if="formData.img" :src="formData.img" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="是否公开" prop="status">
        <el-radio-group v-model="formData.isPublic" disabled v-if="!isEdit">
          <el-radio :label="1">公开</el-radio>
          <el-radio :label="0">不公开</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.isPublic" v-if="isEdit">
          <el-radio :label="1">公开</el-radio>
          <el-radio :label="0">不公开</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="内容">
        <mavonEditor v-model="formData.mdContent" :editable="false" v-if="!isEdit"  />
        <mavonEditor v-model="formData.mdContent" :editable="true" v-if="isEdit" />
      </el-form-item>
      <el-form-item align="center" v-if="isEdit">
        <el-button type="primary" @click="submit('formData')" >确认</el-button>
        <el-button type="danger"  @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {mavonEditor} from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import blogApi from '@/api/blog';
import fileApi from "@/api/file";
export default {
  components:{
    mavonEditor, // 引入markdown编辑器
  },
  props:{
    id: null,  // 文章id
    isEdit:{  // 是否编辑页面
      type: Boolean,
      default: true
    },
    title:{
      type:String,
      default:''
    },
    visiable:{  // 弹出窗口
      type:Boolean,
      default:false
    },
    remoteClose: Function, //用于关闭窗口
  },

  data() {
    return {
      formData: {},
      categoryList: [],
      labelList: [],
      checkedCategoryId: '',
      checkedLabelIds: '',
      categoryName: '',
      categoryId: '',
    }
  },

  watch: {
    // 监听visiable的变化 将改变之后的值传入
    visiable(val) {
      if(val) {
        this.fetchData();
        this.getCategoryAndLabels();
        this.fetchCategory();
      }
    },

    checkedCategoryId (newId, oldId) {
      console.log('改变了分类id')
      console.log(oldId + "====>" + newId)
      if (newId) {
        console.log('重新查询labelIds')
        this.fetchLabel(newId);
      }
      if (newId !== oldId && oldId) {
        console.log('清空了labelIds')
        const bakLabelIds = [];
        this.checkedLabelIds  = '';
      }
    }
  },

  methods: {
    // 提交编辑
    submit() {
      this.formData.createTime = '';
      this.formData.labels = this.checkedLabelIds;
      blogApi.updateArticle(this.formData).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '编辑成功',
            type: 'success',
            duration: 1500
          });
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有操作权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
        this.handleClose();
      })
    },

    // 获取所有的分类信息
    fetchCategory() {
      blogApi.getAllCategory().then(response => {
        if (response.code === 200) {
          this.categoryList = response.data;
        }
      })
    },

    // 根据分类信息的id查询标签信息
    fetchLabel(categoryId) {
      blogApi.getLabelByCategoryId(categoryId).then(response => {
        if (response.code === 200) {
          this.labelList = response.data;
        }
      })
    },

    // 根据文章id获取文章的标签和分类
    getCategoryAndLabels() {
      blogApi.getCategoryAndLabelsByArticleId(this.id).then(response => {
        if (response.code === 200) {
          this.checkedCategoryId = response.data.categoryId;
          this.checkedLabelIds = response.data.labels;
        }
      })
    },

    // 查询博客详情
    fetchData() {
      blogApi.getById(this.id).then(response => {
        if (response.code === 200) {
          this.formData = response.data;
        }
      })
    },

    // 上传图片 file 上传的图片对象
    uploadMainImg(file){
      const data = new FormData();
      data.append('file', file.file);
      fileApi.uploadImage(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200){
          this.formData.img = response.data;
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    // 关闭窗口
    handleClose(){
      // 调用父组件的方法关闭窗口
      this.checkedCategoryId = '';
      this.categoryId = '';
      this.remoteClose();
    },
  }
}
</script>

<style scoped>

</style>
